<?php
/**
 * User: Jerry
 * Date: 2017/8/25
 * Time: 15:07
 */

namespace SDXApi\Service;


use SDXApi\Abstracts\TemplateAbstract;
use SDXApi\Model\HomeTemplateTakeModel;

/**
 * Class HomeTemplateBuyTakeService
 * @author Jerry
 * @package SDXApi\Service
 */
class HomeTemplateBuyTakeService extends TemplateAbstract
{

    /**
     * @var HomeTemplateTakeModel
     */
    protected $takeModel;

    /**
     * HomeTemplateBuyTakeService constructor.
     */
    public function __construct()
    {
        $this->takeModel = new HomeTemplateTakeModel();
    }

    /**
     * @author Jerry
     * @param array $template
     * @param int $userId
     * @param int $wid
     * @return array|bool|mixed
     */
    public function handle($template = array(), $userId = 0, $wid = 8)
    {
        $cacheName = 'home_template_take_id_' . $template['id'];

        $data = $this->getCache($cacheName);

        if (empty($data)) {
            $data = $this->getTakeIds($template);

            if (! empty($data)) {
                $this->cacheData($cacheName, $data, mt_rand(3600, 4200));
            }
        }

        return $data;
    }

    /**
     * @author Jerry
     * @param array $template
     * @return array|bool
     */
    protected function getTakeIds($template = array())
    {
        $categoryId = $this->takeModel->findTakeByTemplateId($template['id']);
        $ids = $this->getCategoryIds($categoryId);

        if (empty($ids)) {
            return false;
        }

        $template['take_data'] = $ids;

        return $template;
    }

    /**
     * @author Jerry
     * @param array $vogue
     * @return bool|string
     */
    protected function getCategoryIds($vogue = array())
    {
        if (empty($vogue)) {
            return false;
        }

        $vogueIds = array();
        foreach ($vogue as $key => $value) {
            $vogueIds[] = $value['classify_id'];
        }

        return implode(',', $vogueIds);
    }
}